var trackArr = new Array();

$('#startTime').datetimepicker({
    minView: "month",
    language:  'zh-CN',
    pickerPosition: "top-right",
    autoclose:true
});

$('#endTime').datetimepicker({
    minView: "month",
    language:  'zh-CN',
    pickerPosition: "top-left",
    autoclose:true
});
$('#startTimeBtn').on('click',function(){
    $('#startTime').datetimepicker('show');
})
$('#endTimeBtn').on('click',function(){
    $('#endTime').datetimepicker('show');
})

var swiper = new Swiper('#date-track', {
    direction: 'horizontal',
    slidesPerView: 1,
    spaceBetween: 30,
    mousewheelControl: true,
    prevButton:'.swiper-button-prev-date',
    nextButton:'.swiper-button-next-date',
    onSlideChangeStart: function(swiper){

    },
    onSlideChangeEnd: function(swiper){
        var slide = swiper.slides[swiper.activeIndex];
        getPosInfos($(slide).attr('trackId'), parseInt($(slide).attr('start')), parseInt($(slide).attr('end')));
    }
});

var swiper1 = new Swiper('#single-track', {
    direction: 'horizontal',
    slidesPerView: 1,
    spaceBetween: 30,
    mousewheelControl: true,
    prevButton:'.swiper-button-prev-single',
    nextButton:'.swiper-button-next-single',
    onSlideChangeEnd: function(swiper){
        var slide = swiper.slides[swiper.activeIndex];
        getPosInfos($(slide).attr('trackId'), parseInt($(slide).attr('start')), parseInt($(slide).attr('end')));
    }
});

$('#date-track').on('click','.track-oper-enter', function(){
    $('#date-track').hide();
    $('#single-track').show();
    swiper1.update();
    initsingleSlide(swiper1, $(this).attr('date'));
});

$('#single-track').on('click','.track-oper-return', function(){
    $('#date-track').show();
    $('#single-track').hide();
    swiper.update();
});
$('#single-track').on('click','.track-oper-hide', function(){
    $(this).parent('p').replaceWith('<p class="text-muted">已隐藏</p>');
    var date = $(this).attr('date');
    var trackId = $(this).attr('trackid');
    $.each(trackArr, function(i){
      if(trackArr[i].date == date){
          var tracks = trackArr[i].tracks.tracks
          $.each(tracks, function(j){
              if(tracks[j].desc.trackId == trackId){
                  tracks[j].display = 'hide';
              }
          })
      }
    });
    $.ajax({
        type: "GET",
        async: true,
        dataType: "json",
        url: "track/hideTrack?deviceId="+deviceId+"&trackId="+trackId,
        success: function(result){
        }
    })
});


var today = (new Date()).Format("yyyy-MM-dd");
var yesterday = (addDate(new Date(), -1)).Format("yyyy-MM-dd");
var dayBeforeYesterday = (addDate(new Date(), -2)).Format("yyyy-MM-dd");
var preweek = (addDate(new Date(), -6)).Format("yyyy-MM-dd");
$("#endTime").val(today);
$("#startTime").val(preweek);


$("#today-content,#yesterday-content,#day-before-yesterday-content,#week-content").on('click',function(){
    var dd = null;
    if(trackArr.length > 0){
        if(this.id == "today-content"){
            dd = (new Date()).Format("yyyy-MM-dd");
        }else if(this.id == "yesterday-content"){
            dd = (addDate(new Date(), -1)).Format("yyyy-MM-dd");
        }else if(this.id == "day-before-yesterday-content"){
            dd = (addDate(new Date(), -2)).Format("yyyy-MM-dd");
        }
        var display = false;
        for(var item in trackArr){
            if(trackArr[item]['date'] == dd){
                display = true;
                break;
            }
        }
        if(this.id == "week-content" || display){
            $("#track-list-container").hide();
            $("section").show();
            $("#single-track").hide();
            initdateSlide(swiper, dd);
        }
    }
})

$("#search").on('click',function(){
    var start = (new Date($("#startTime").val())).getTime();
    var end = (new Date($("#endTime").val())).getTime()+24*60*60*1000 -1;
    if(end < start){
        alertWarn(false, "开始时间不能大于结束时间!")
    }else if(end - start > 7*24*60*60*1000){
        alertWarn(false, "只能查一周内的数据!");
    }else{
        $(this).button('loading');
        $.ajax({
            type: "GET",
            async: true,
            dataType: "json",
            url: "track/getTracks?deviceId="+deviceId+"&start="+start+"&end="+end,
            success: function(result){
                if(result && result.code == '200'){
                    var sum = result.data.sum;
                    var dailys = result.data.dailys;
                    if(sum && sum['mileages'] && sum['mileages']>0){
                        trackArr = [];
                        $.each(dailys, function(i){
                            if(dailys[i]['mileages']){
                                var obj = {};
                                obj.date = dailys[i]['date'];
                                obj.tracks = dailys[i];
                                trackArr.push(obj);
                            }
                        })
                        $("#track-list-container").hide();
                        $("section").show();
                        $("#single-track").hide();
                        initdateSlide(swiper);
                    }else{
                        alertWarn(false, "时间段内没有轨迹信息")
                    }
                }else if(result.code == 401){
                    refreshToken();
                    alertWarn(false, "您可能重新绑定了终端, 请重试!");
                }else if(result.code == 404){
                    alertWarn(false, "此时间段内没有轨迹信息");
                }else{
                    alertWarn(false, "获取行程信息失败")
                }
            },
            error: function(xhr,status,statusText){
                alertWarn(false, "获取行程信息失败");
            },
            complete: function(){
                $("#search").button('reset');
            }
        })
    }

})


function init(deviceid){
    deviceId = deviceid;
    var todaySlot = getTimeSlotFromDay(new Date());
    var preWeekSlot = getTimeSlotFromDay(addDate(new Date(), -6));
    initTrack(deviceId,preWeekSlot.start, todaySlot.end);
}
function initTrack(deviceId,start,end){
    $.ajax({
        type: "GET",
        async: true,
        dataType: "json",
        url: "track/getTracks?deviceId="+deviceId+"&start="+start+"&end="+end,
        success: function(result){
            if(result && result.code == '200'){
                var dailys = result.data.dailys;
                $.each(dailys, function(i){
                    if(dailys[i]['mileages']){
                        var obj = {};
                        obj.date = dailys[i]['date'];
                        obj.tracks = dailys[i];
                        trackArr.push(obj);
                    }
                    if(dailys[i]['date'] == (new Date()).Format("yyyy-MM-dd")){
                        $("#today-tab h4").find('span').eq(1).text(dailys[i]['date']);
                        if(dailys[i]['mileages']){
                            //有轨迹信息
                            $("#today-tab h4").find('span').eq(2).text('共有'+dailys[i]['tracks'].length+'段轨迹');

                            $("#today-content h3").find('span').eq(0).html($("#today-content h3").find('span').eq(0).html() + dailys[i]['mileages']+'km');
                            $("#today-content h3").find('span').eq(1).html($("#today-content h3").find('span').eq(1).html() + dailys[i]['speed']+'km/h');
                            $("#today-content h3").find('span').eq(2).html($("#today-content h3").find('span').eq(2).html() + dailys[i]['score']+'分');
                        }else{
                            //没有轨迹信息
                            $("#today-content").addClass('text-center');
                            $("#today-content h3").html('<i class="fa fa-info-circle text-muted"></i>' +
                                '<span class="text-muted">没有轨迹信息</span>')
                        }
                    }else if(dailys[i]['date'] == (addDate(new Date(), -1)).Format("yyyy-MM-dd")){
                        $("#yesterday-tab h4").find('span').eq(1).text(dailys[i]['date']);
                        if(dailys[i]['mileages']){
                            //有轨迹信息
                            $("#yesterday-tab h4").find('span').eq(2).text('共有'+dailys[i]['tracks'].length+'段轨迹');

                            $("#yesterday-content h3").find('span').eq(0).html($("#yesterday-content h3").find('span').eq(0).html() + dailys[i]['mileages']+'km');
                            $("#yesterday-content h3").find('span').eq(1).html($("#yesterday-content h3").find('span').eq(1).html() + dailys[i]['speed']+'km/h');
                            $("#yesterday-content h3").find('span').eq(2).html($("#yesterday-content h3").find('span').eq(2).html() + dailys[i]['score']+'分');
                        }else{
                            //没有轨迹信息
                            $("#yesterday-content").addClass('text-center');
                            $("#yesterday-content h3").html('<i class="fa fa-info-circle text-muted"></i>' +
                                '<span class="text-muted">没有轨迹信息</span>')
                        }
                    }else if(dailys[i]['date'] == (addDate(new Date(), -2)).Format("yyyy-MM-dd")){
                        $("#day-before-yesterday-tab h4").find('span').eq(1).text(dailys[i]['date']);
                        if(dailys[i]['mileages']){
                            //有轨迹信息
                            $("#day-before-yesterday-tab h4").find('span').eq(2).text('共有'+dailys[i]['tracks'].length+'段轨迹');

                            $("#day-before-yesterday-content h3").find('span').eq(0).html($("#day-before-yesterday-content h3").find('span').eq(0).html() + dailys[i]['mileages']+'km');
                            $("#day-before-yesterday-content h3").find('span').eq(1).html($("#day-before-yesterday-content h3").find('span').eq(1).html() + dailys[i]['speed']+'km/h');
                            $("#day-before-yesterday-content h3").find('span').eq(2).html($("#day-before-yesterday-content h3").find('span').eq(2).html() + dailys[i]['score']+'分');
                        }else{
                            //没有轨迹信息
                            $("#day-before-yesterday-content").addClass('text-center');
                            $("#day-before-yesterday-content h3").html('<i class="fa fa-info-circle text-muted"></i>' +
                                '<span class="text-muted">没有轨迹信息</span>')
                        }
                    }
                })
                var sum = result.data.sum;
                if(sum['mileages']){
                    //有轨迹信息
                    $("#week-tab h4").find('span').eq(1).text((addDate(new Date(), -6)).Format("MM/dd") +'~'+ (new Date()).Format("MM/dd"));
                    //$("#week-tab h4").find('span').eq(2).text('共有4段轨迹');

                    $("#week-content h3").find('span').eq(0).html($("#week-content h3").find('span').eq(0).html() + sum['mileages']+'km');
                    $("#week-content h3").find('span').eq(1).html($("#week-content h3").find('span').eq(1).html() + sum['speed']+'km/h');
                    $("#week-content h3").find('span').eq(2).html($("#week-content h3").find('span').eq(2).html() + sum['score']+'分');
                }else{
                    //没有轨迹信息
                    $("#week-content").addClass('text-center');
                    $("#week-content h3").html('<i class="fa fa-info-circle text-muted"></i>' +
                        '<span class="text-muted">没有轨迹信息</span>')
                }
                //alert(JSON.stringify(result));
            }else if(result && result.code == 401){
                refreshToken();
                alertWarn(false, "您可能重新绑定了终端, 请重试!");
            }else if(result && result.code == 404){
                $("#today-content").addClass('text-center');
                $("#today-content h3").html('<i class="fa fa-info-circle text-muted"></i>' +
                    '<span class="text-muted">没有轨迹信息</span>');

                $("#yesterday-content").addClass('text-center');
                $("#yesterday-content h3").html('<i class="fa fa-info-circle text-muted"></i>' +
                    '<span class="text-muted">没有轨迹信息</span>');

                $("#day-before-yesterday-content").addClass('text-center');
                $("#day-before-yesterday-content h3").html('<i class="fa fa-info-circle text-muted"></i>' +
                    '<span class="text-muted">没有轨迹信息</span>');

                $("#week-content").addClass('text-center');
                $("#week-content h3").html('<i class="fa fa-info-circle text-muted"></i>' +
                    '<span class="text-muted">没有轨迹信息</span>');

            }else{
                alertWarn(false, "获取行程信息失败");
            }
            $(".loading-mask").hide();
        },
        error: function(xhr,status,statusText){
            alertWarn(false, "获取行程信息失败");
            $(".loading-mask").hide();
        }
    })
}

function initdateSlide(swiper, dd){
    swiper.removeAllSlides();
    var slideToIndex = 0;
    trackArr.sort(function(v1,v2){
        return v1.date.replace(new RegExp("-",'gm'),"") - v2.date.replace(new RegExp("-",'gm'),"");
    })
    $.each(trackArr, function(i){
        var tracks = trackArr[i].tracks.tracks;
        var slide = '<div class="swiper-slide" trackid="'+tracks[0].desc.trackId+'" start="'+tracks[0].desc.trackStart+'" end="'+tracks[0].desc.trackStop+'">'+
            '<div class="col col-xs-6 track-oper">' +
            '<p>'+trackArr[i].date+'</p>' +
            '<p><a href="#" class="track-oper-enter" date="'+trackArr[i].date+'">进入</a></p>'+
            '</div>'+
            '<div class="col col-xs-6 track-info">'+
            '<p class="text-left"><img height="14" src="/wx/images/track_odo.png"/>'+trackArr[i].tracks.mileages+'km</p>'+
            '<p class="text-left"><img height="14" src="/wx/images/track_avg_speed.png"/>'+trackArr[i].tracks.speed+'km/h</p>'+
            '<p class="text-left"><img height="14" src="/wx/images/track_score.png"/>'+trackArr[i].tracks.score+'分</p>'+
            '</div>'+
            '</div>'
        if(dd == trackArr[i].date){
            slideToIndex = i;
        }
        swiper.appendSlide(slide);
    })
    if(slideToIndex > 0){
        swiper.slideTo(slideToIndex);
    }else{
        var headerDesc = trackArr[0].tracks.tracks[0].desc;
        getPosInfos(headerDesc.trackId, headerDesc.trackStart, headerDesc.trackStop);
    }
}

function initsingleSlide(swiper, date){
    swiper.removeAllSlides();
    $.each(trackArr,function(i){
        if(trackArr[i].date == date){
            var tracks = trackArr[i].tracks.tracks;
            $.each(tracks, function(j){
                var start = tracks[j].desc.trackStart;
                var end = tracks[j].desc.trackStop;
                var operShow = '<p><a href="#" class="track-oper-hide" date="'+ trackArr[i].date +'" trackid="'+tracks[j].desc.trackId+'">隐藏</a></p>';
                if(tracks[j].display == "hide"){
                    operShow = '<p class="text-muted">已隐藏</p>'
                }
                var slide = '<div class="swiper-slide" trackid="'+tracks[j].desc.trackId+'" start="'+start+'" end="'+end+'">'+
                    '<div class="col col-xs-6 track-oper">'+
                    '<p>'+ (new Date(start)).Format('hh:mm') + '~' + (new Date(end)).Format('hh:mm') + '</p>'+
                    '<p><a href="#" class="track-oper-return">返回</a></p>'+
                    operShow+
                    '</div>'+
                    '<div class="col col-xs-6 track-info">' +
                    '<p class="text-left"><img height="14" src="/wx/images/track_odo.png"/>'+tracks[j].statistics.totalMileage+'km</p>' +
                    '<p class="text-left"><img height="14" src="/wx/images/track_avg_speed.png"/>'+tracks[j].statistics.avgSpeed+'km/h</p>' +
                    '<p class="text-left"><img height="14" src="/wx/images/track_score.png"/>'+tracks[j].statistics.score+'分</p>' +
                    '</div></div>'
                swiper.appendSlide(slide);
            })
            var headerDesc = tracks[0].desc;
            getPosInfos(headerDesc.trackId, headerDesc.trackStart, headerDesc.trackStop);

        }
    })

}

function getPosInfos(trackId, start, end){
    $.ajax({
        type: "GET",
        async: true,
        dataType: "json",
        url: "track/searchPoss?deviceId="+deviceId+"&start=" + start + "&end=" + end + "&trackId="+trackId,
        success: function (result) {
            if(result && result.code == 200 && result.data.length > 0){
                var datas = result.data;
                var pois = [];
                $.each(datas, function(i){
                    pois.push(new qq.maps.LatLng(datas[i].lat, datas[i].lng));
                })
                qq.maps.convertor.translate(pois, 1, function(res){
                    initMap(res, (new Date(start)).Format('hh:mm'), (new Date(end)).Format('hh:mm'));
                })
            }else if(result.code == 401){
                refreshToken();
                alertWarn(false, "您可能重新绑定了终端, 请重试!");
            }else{
                alertWarn(false, "获取行程gps信息失败")
            }
        }
    })
}

function initMap(poss, start, end){
    if(poss && poss.length > 0){
        $("#map-container").empty();
        var center = poss[0];
        map = new qq.maps.Map(document.getElementById("map-container"), {
            center: center,
            zoom:13
        });
        new qq.maps.Polyline({//画轨迹线
            path: poss,
            strokeColor: '#1c29d8',
            strokeWeight: 5,
            editable:false,
            map:map
        });
        markerStartEnd(map,poss[0],poss[poss.length-1],start,end);
    }
}

function markerStartEnd(map,startPoint,endPoint,startTime,endTime){
    var anchor=new qq.maps.Point(20,41),//图标的相对左上角的偏移量
        size=new qq.maps.Size(41,41),
        origin=new qq.maps.Point(0,0),//显示图标全部分
        icon=new qq.maps.MarkerImage('/wx/images/start.png',size,origin,anchor);
    new qq.maps.Marker({icon:icon,map:map,position:startPoint});//轨迹开始标记
    new qq.maps.Label({ position: startPoint, map: map, content:startTime});//轨迹开始的时间标记
    icon=new qq.maps.MarkerImage('/wx/images/end.png',size,origin,anchor);
    new qq.maps.Marker({icon:icon,map:map,position:endPoint});//轨迹结束标记
    new qq.maps.Label({ position: endPoint, map: map, content:endTime});//轨迹结束的时间标记
}

function initWxConfig(){
    var url = location.href.split('#')[0];
    $.ajax({
        type: "GET",
        async: true,
        dataType: "json",
        url: "/share/getWxJsConfig?url="+encodeURIComponent(url),
        success: function(data){
            if(data){
                wxConfig(data);
            }
        },
        error: function(xhr,status,statusText){
            alertWarn(false, "获取微信配置信息失败");
        }
    })
}

function wxConfig(data) {
    wx.config({
        debug: false,
        appId: data.appId,
        timestamp: data.timestamp,
        nonceStr: data.nonceStr,
        signature: data.signature,
        jsApiList: [
            // 所有要调用的 API 都要加到这个列表中
        ]
    });
}

wx.ready(function(){
    wx.hideOptionMenu();
})



